package org.hawk.gwt.ppc.parser.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.hawk.gwt.ppc.parser.Descriptor;
import org.hawk.gwt.ppc.parser.Token;

/**
 * General implementation of descriptor methods.
 * 
 * @author alex.bereznevatiy@gmail.com
 *
 */
abstract class AbstractDescriptor implements Descriptor {
	
	private List<Token> tokens;
	private Descriptor parent;

	AbstractDescriptor() {
		tokens = new ArrayList<Token>();
	}

	/**
	 * @param list
	 * @return unmodifiable list created based on passed list.
	 * {@link ArrayList} will be trimed to size.
	 */
	static <T> List<T> unmodify(List<T> list) {
		if (list.isEmpty()) {
			return Collections.emptyList();
		}
		if (list instanceof ArrayList) {
			((ArrayList<?>)list).trimToSize();
		}
		return Collections.unmodifiableList(list);
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.hawk.gwt.ppc.parser.Descriptor#getTokens()
	 */
	public List<Token> getTokens() {
		return Collections.unmodifiableList(tokens);
	}
	
	void addToken(Token token) {
		tokens.add(token);
	}

	/*
	 * (non-Javadoc)
	 * @see org.hawk.gwt.ppc.parser.Descriptor#replace(java.lang.CharSequence)
	 */
	public List<Descriptor> replace(CharSequence replacement) {
		throw new UnsupportedOperationException();
	}

	/*
	 * Reference to parent container.
	 * Sometimes used by child descriptors.
	 */
	Descriptor getParent() {
		return parent;
	}

	void setParent(Descriptor parent) {
		this.parent = parent;
	}
}
